import axios from 'axios';
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,message,Upload } from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined,EllipsisOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
import { useParams } from 'react-router-dom';
const CorrectionPage = () => {
  const navigate = useNavigate();
  const { TextArea } = Input;
  const { courseid, homeworkid } = useParams();
  const [form] = useForm();
  const [data, setData] = useState([]);
  const [length, setlength] = useState('');
  const [editedData, setEditedData] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [params,setParams] = useState({
    page:1,
    perpage:5
  })
  useEffect(() => {
    axios.get('http://localhost:8000/getstudenthomework', {
      params: { ...params, courseid,homeworkid }
      })
      .then(response => {
        console.log("接受到的数据"+response.data.list);
        setData(response.data.list);
        setlength(response.data.length);
        console.log("存储到的数据"+JSON.stringify(data));
       // console.log(params); // Updated data
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, [params]);

  useEffect(() => {
    //console.log(editedData);
    if (editedData !== null) {
      form.setFieldsValue({
        homeworkid: editedData?.homeworkid,
        title: editedData?.title,
        text: editedData?.text,
        img: editedData?.img,
        start: editedData?.start,
        score: editedData?.score,
        // 其他字段...
      });
      setIsModalVisible(true);
    }
  }, [editedData, form]);

  const change = (data) => {
    console.log(data);
    setEditedData(data);
    setIsModalVisible(true);
  }
  const handleOk = () => {
    const Id = editedData?.id;
    const values = form.getFieldsValue(); // 获取表单修改后的值
    console.log('修改后的表单值:', values, Id);
    axios.post('http://localhost:8000/correcthomework', { Id, values,params })
      .then(response => {
        // 处理来自后端的响应
        console.log('成功发送到后端并收到响应:', response.data);
        setIsModalVisible(false);
        axios.get('http://localhost:8000/getstudenthomework', {
          params: { ...params, courseid,homeworkid }
          })
          .then(response => {
            console.log("接受到的数据"+response.data.list);
            setData(response.data.list);
            setlength(response.data.length);
            console.log("存储到的数据"+JSON.stringify(data));
           // console.log(params); // Updated data
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
      });
  };
  

  const handleCancel = () => {
    setIsModalVisible(false);
    //setEditedData([])
  };


  
    // 翻页实现
    const pageChange = (page) => {
      setParams({
        ...params,
        page
      })
    }

  const columns = [
    {
      title: '作业编号',
      dataIndex: 'homeworkid',
      width: 220
    },
    {
      title: '学生姓名',
      dataIndex: 'studentname',
    },
    {
      title: '成绩',
      dataIndex: 'score',
      render: score => (
        <span style={{ color: score === null ? 'red' : 'inherit' }}>
          {score === null ? '未批改' : score}
        </span>
      )
    },
    {
      title: '操作',
      width: 220,
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => change(data)}  
            />
            
          </Space>
        )
      },
      fixed: 'right'
    }
  ]

  return (
    <div>
      <Breadcrumb>
        <Breadcrumb.Item><Link to="/Layoutteacher/coursepage">Courses</Link></Breadcrumb.Item>
        <Breadcrumb.Item><Link to={`/Layoutteacher/course/${courseid}`}>课程详情</Link></Breadcrumb.Item>
        <Breadcrumb.Item><Link to={`/Layoutteacher/homework/${courseid}`}>课程详情</Link></Breadcrumb.Item>
        <Breadcrumb.Item>作业批改</Breadcrumb.Item>
      </Breadcrumb>
      <Card >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          pagination={
            {
              pageSize: params.perpage,
              onChange: pageChange,
              current: params.page,
              total: length
            }
          }
        />
      </Card>
      <Modal
  title="批改作业"
  visible={isModalVisible}
  onOk={handleOk}
  onCancel={handleCancel}
  width={800}
>
  <Form
    form={form}
    labelCol={{ span: 6 }}
    wrapperCol={{ span: 16 }}
  >
    {/* 表单字段 */}
    <Form.Item label="作业编号" name="courseid" initialValue={editedData?.courseid}>
    <span>{editedData?.courseid}</span>
    </Form.Item>
    <Form.Item label="作业编号" name="homeworkid" initialValue={editedData?.homeworkid}>
    <span>{editedData?.homeworkid}</span>
    </Form.Item>
    <Form.Item label="作业内容" name="text" initialValue={editedData?.text}>
    <TextArea 
    readOnly
    style={{ width: '500px', height: '500px', textAlign: 'left' }} // 控制文本水平对齐
/>
  </Form.Item>
  <Form.Item label="作业图片" name="img" initialValue={editedData?.img}>
  {editedData?.img && (
    editedData.img.includes(',') ? 
    editedData.img.split(',').map((img, index) => (
        <img key={index} src={`http://localhost:8000/${img.trim()}`} alt={`Image ${index}`} style={{ maxWidth: '400px', maxHeight: '400px', marginRight: '100px' }} />
      )) : 
      <img src={`http://localhost:8000/${editedData.img.trim()}`} alt="Single Image" style={{ maxWidth: '100px', maxHeight: '100px' }} />
      
  )}
    </Form.Item>
    <Form.Item label="作业成绩" name="score" initialValue={editedData?.score}>
    <Input style={{ width: 200 }} />
</Form.Item>

  </Form>
</Modal>
    </div>
  );
};

export default CorrectionPage;